package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.ValidateCodeService;
import com.itheima.util.SMSUtils;
import com.itheima.util.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @author hql
 * @date 2019-12-10 9:37
 */
@Service
public class ValidateCodeImpl implements ValidateCodeService {

    @Autowired
    private JedisPool jedisPool;
    @Override
    public Result sendCode(String telephone) {
        return sendCode(telephone, 4, RedisMessageConstant.SENDTYPE_ORDER);
    }


    @Override
    public Result send4Login(String telephone) {
        return sendCode(telephone, 6, RedisMessageConstant.SENDTYPE_LOGIN);
    }


    /**
     * 发送验证码
     * @param telephone
     * @param i
     * @param sendtypeOrder
     * @return
     */

    private Result sendCode(String telephone, int i, String sendtypeOrder) {
        String code = ValidateCodeUtils.generateValidateCode4String(i);
        //体检预约发送验证码
        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, code);
            //将验证码保存到jedis时长为5分钟,键为手机号
            jedisPool.getResource().setex(telephone + sendtypeOrder, 300, code);
            jedisPool.getResource().close();
        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }





    /**
     * 校验验证码的正确性
     * @param telphone 手机号
     * @param validateCode 验证码
     * @param redisMessageConstant 所定义的手机号后缀的验证码类型
     * @return
     */
    public  boolean  checkValidateCode(String telphone,String validateCode,String redisMessageConstant){
        Jedis jedis = jedisPool.getResource();
        if (validateCode!=null) {
            if (validateCode.equals(jedis.get(telphone+redisMessageConstant))){
                //登录成功后删除验证码
                //jedis.del(telphone+redisMessageConstant);
            }else {
                return false;
            }
        }
        jedis.close();
        return true;
    }
}
